package com.tz.farmer.util;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.aliyun.oss.*;
import com.aliyun.oss.model.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @program: smartPark
 * @description: Oss工具类
 * @author: zje
 * @create: 2020-11-24 21:19
 */
public class OssUtils {

    private static final Logger logger = LoggerFactory.getLogger(OssUtils.class);

    public static final String BUCKETNAME = "smark-study-online";
    public static final String ACCESSKEYID = "LTAI4G1Libs4e89wijUD91Yd";
    public static final String ACCESSKEYSECRET = "DvwAn9AqTJPXNgwUq4j3KkdH28cXBt";
    public static final String ENDPOINT = "https://oss-cn-hangzhou.aliyuncs.com";   //根路径
    public static final String URL = "https://smark-study-online.oss-cn-hangzhou.aliyuncs.com/";

    //默认填写ENDPOINT、ACCESSKEYID、ACCESSKEYSECRET
    public static OSS getOssInstance() {
        return new OSSClientBuilder().build(ENDPOINT, ACCESSKEYID, ACCESSKEYSECRET);
    }

    /**
     * 简单上传单文件
     * @param multipartFile
     * @param folderName
     * @return
     */
    public static String uploadOssFile(MultipartFile multipartFile, String folderName) {
        OSS ossClient = null;
        String url = "";
        try{
            // meta设置请求头,解决访问图片地址直接下载
            ObjectMetadata meta = new ObjectMetadata();
            meta.setContentType(FileUtils.getContentType(folderName.substring(folderName.lastIndexOf("."))));
            ossClient = new OSSClientBuilder().build(ENDPOINT,ACCESSKEYID,ACCESSKEYSECRET);
            ossClient.putObject(BUCKETNAME, folderName , multipartFile.getInputStream(),meta);  //哪个bucket （bucketName） 下的哪个文件中（key）
            url = URL + "/" + folderName;
        }catch (IOException ie){
            url = "400" + ":" + ie.getMessage();
        }catch (OSSException oe) {
            url = oe.getErrorCode() + ":" + oe.getErrorMessage();
        }catch (ClientException ce) {
            url = ce.getErrorCode() + ":" + ce.getMessage();
        }finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return url;
    }


    public static void downLoad(HttpServletRequest request, HttpServletResponse response, String urlString) throws IOException {
        response.reset();
        response.setContentType("application/x-msdownload");
        response.setHeader("Content-Disposition","attachment;filename=" + new String(urlString.getBytes("utf-8"),"ISO8859-1"));
        OSSClient ossClient = new OSSClient(ENDPOINT,ACCESSKEYID,ACCESSKEYSECRET);

        String 	key = urlString.toString();
        key = key.replaceAll("\\\\", "/");
        OSSObject object = ossClient.getObject(BUCKETNAME, key);
        BufferedInputStream input = new BufferedInputStream(object.getObjectContent());
        byte[] buffBytes = new byte[1024];
        OutputStream outputStream = response.getOutputStream();
        int read = 0;
        while ((read = input.read(buffBytes)) != -1) {
            outputStream.write(buffBytes, 0, read);
        }

        outputStream.flush();
        outputStream.close();
        //is.close();
        input.close();
        ossClient.shutdown();

    }





}


/**
 *
 AccessDenied 拒绝访问 403
 BucketAlreadyExists Bucket已经存在 409
 BucketNotEmpty Bucket不为空 409
 EntityTooLarge 实体过大 400
 EntityTooSmall 实体过小 400
 FileGroupTooLarge 文件组过大 400
 FilePartNotExist 文件Part不存在 400
 FilePartStale 文件Part过时 400
 InvalidArgument 参数格式错误 400
 InvalidAccessKeyId AccessKeyId不存在 403
 InvalidBucketName 无效的Bucket名字 400
 InvalidDigest 无效的摘要 400
 InvalidObjectName 无效的Object名字 400
 InvalidPart 无效的Part 400
 InvalidPartOrder 无效的part顺序 400
 InvalidTargetBucketForLogging Logging操作中有无效的目标bucket 400
 InternalError OSS内部发生错误 500
 MalformedXML XML格式非法 400
 MethodNotAllowed 不支持的方法 405
 MissingArgument 缺少参数 411
 MissingContentLength 缺少内容长度 411
 NoSuchBucket Bucket不存在 404
 NoSuchKey 文件不存在 404
 NoSuchUpload Multipart Upload ID不存在 404
 NotImplemented 无法处理的方法 501
 PreconditionFailed 预处理错误 412
 RequestTimeTooSkewed 发起请求的时间和服务器时间超出15分钟 403
 RequestTimeout 请求超时 400
 SignatureDoesNotMatch 签名错误 403
 InvalidEncryptionAlgorithmError 指定的熵编码加密算法错误 400
 * @param root
 * @param imgurl
 * @return
 */
